package com.fudan.adse.service.impl;

import com.fudan.adse.component.GrpcServiceStub;
import com.fudan.adse.domain.bo.UserBO;
import com.fudan.adse.domain.dto.AdminUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;


/**
 * @author Jerry Zhang <zhangjian16@fudan.edu.cn>
 * @desc UserService实现类
 * @date 2022-09-14 12:03
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private GrpcServiceStub grpcServiceStub;
    @Autowired
    private HttpServletRequest request;

    /**
     * 获取用户信息
     *
     * @param username
     * @return
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String clientId = request.getParameter("client_id");
        UserBO userBO = grpcServiceStub.loadUserByUsername(username);
        if (userBO == null) {
            log.info("用户名或密码错误");
            throw new UsernameNotFoundException("用户名或密码错误!");
        }
        AdminUserDetails adminUserDetails = new AdminUserDetails(userBO);
        adminUserDetails.setClient(clientId);
        if (!adminUserDetails.isEnabled()) {
            throw new DisabledException("该账户已被禁用，请联系管理员!");
        } else if (!adminUserDetails.isAccountNonLocked()) {
            throw new LockedException("该账号已被锁定，请联系管理员!");
        } else if (!adminUserDetails.isAccountNonExpired()) {
            throw new AccountExpiredException("该账号已过期，请联系管理员!");
        } else if (!adminUserDetails.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException("该账户的登录凭证已过期，请重新登录!");
        }
        return adminUserDetails;
    }
}

